import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import * as echarts from 'echarts';
import dayjs from 'dayjs';
import ECharts from '@kuiper-components/echarts';

import { datetime, number } from '../../../../../common/formatter';
import { WARNING_CATEGORY_KEY_LABEL_MAP } from '../../../../../common/constants';

import RadioButton, {
	Group as RadioGroup,
} from '../../../../components/RadioButton';
import Helper from '../../../../components/Helper';
import Box from '../Box';
import s from './Trend.module.css';

const numFormat = number;

export default function Trend({ className, dateRask = {}, stats }) {
	const taskQuickMark = dateRask.detectTime;
	const [type, setType] = React.useState('_ALL_');
	const [myChart, setChart] = React.useState(undefined);
	const emptyLineData = []
	for (let i = 7; i >= 1; i--) {
		emptyLineData.push([
			dayjs().subtract(i, 'days').startOf('day').toDate(),
			0,
			{}
		]);
	}
	const option = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross',
			},
			formatter([
				{
					data: [date, count, stats],
					seriesName,
				},
			]) {
				return `
					<div>
						<div
							style="width: 100%; text-align: left; border-bottom: 1px solid var(--color-border-2); padding: 0.5rem 0.75rem; margin-bottom: 0.25rem;"
						>
							${datetime(date)}
						</div>
						<table style="width: 100%;">
							<tbody>
								${
									type === '_ALL_'
										? `
											<tr>
												<td style="padding: 0.25rem 0.5rem;">风险URL总数</td>
												<td style="text-align: right; padding: 0.5em;">${numFormat(count)}个</td>
											</tr>
											<tr>
												<td style="padding: 0.25rem 0.5rem;">含敏感词URL数</td>
												<td style="text-align: right; padding: 0.5em;">${numFormat(
													stats?.keyword
												)}个</td>
											</tr>
											<tr>
												<td style="padding: 0.25rem 0.5rem;">含隐私信息URL数</td>
												<td style="text-align: right; padding: 0.5em;">${numFormat(
													stats?.privacy_disclosure
												)}个</td>
											</tr>
										`
										: `<tr>
												<td style="padding: 0.25rem 0.5rem;">含${
													WARNING_CATEGORY_KEY_LABEL_MAP.content?.[type]
												}URL数</td>
												<td style="text-align: right; padding: 0.25rem 0.5rem;">
													${numFormat(count)}个
												</td>
											</tr>`
								}
							</tbody>
						</table>
					</div>
				`;
			},
			backgroundColor: '#fff',
			textStyle: '#696C78',
			extraCssText:
				'min-width: 10rem; color: var(--color-text-1); line-height: 1rem; margin: 0 auto; box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);',
		},
		axisPointer: {
			show: true,
			lineStyle: {
				width: 2,
				type: 'dotted',
				color: '#F0443C',
			},
		},
		grid: {
			left: '48',
			right: '110',
			top: '24',
			bottom: '48',
		},
		xAxis: {
			type: 'time',
			boundaryGap: false,
			splitNumber: 7,
			splitLine: { show: false },
			axisLine: { lineStyle: { color: 'transparent' }, show: false },
			axisTick: {
				show: false,
			},
			axisLabel: {
				showMaxLabel: false,
				formatter(value) {
					const date = new Date(value);
					return datetime(date, 'YYYY-MM-DD HH:mm:ss');
				},
				margin: 20,
				align: 'left',
			},
		},
		yAxis: {
			type: 'value',
			boundaryGap: false,
			axisTick: {
				show: false,
			},
			splitLine: { lineStyle: { color: '#F7F9FC' }, show: true },
			axisLine: { lineStyle: { color: 'transparent' }, show: false },
		},
		textStyle: { color: '#696C78', fontSize: 12 },
		series: [
			{
				data: emptyLineData,
				name: '全部',
				type: 'line',
				smooth: true,
				smoothMonotone: 'x',
				showSymbol: false,
				lineStyle: {
					color: '#FAAF2C',
					width: 2,
				},
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{
							offset: 0,
							color: 'rgba(255, 165, 78, 0.4977)',
						},
						{
							offset: 1,
							color: 'rgba(249, 222, 105, 0.0001)',
						},
					]),
				},
			},
		],
	};

	if (stats?.length) {
		if (type === '_ALL_') {
			option.series[0].data = stats.map(({ endTime, result: { stats } }) => [
				endTime,
				stats?.url || 0,
				stats,
			]);
		} else {
			option.series[0].data = stats.map(({ endTime, result: { stats } }) => [
				endTime,
				stats?.[type] || 0,
				stats,
			]);
		}
		option.series[0].data.sort(
			(a, b) => new Date(a[0]).getTime() - new Date(b[0]).getTime()
		);
		while (option.series[0].data.length < 10) {
			option.series[0].data.unshift([
				dayjs(option.series[0].data[0][0])
					.subtract(1, 'days')
					.toDate()
					.getTime(),
				0,
				{},
			]);
		}
		const max = option.series[0].data.reduce((max, b) => {
			if (b[1] > max) return b[1];
			return max;
		}, 10);
		option.yAxis.max = max + 3;
	} else if (dateRask.dateRange) {
		option.series[0].data = [
			[Date.parse(dateRask.dateRange[0]), 0, {}],
			[Date.parse(dateRask.dateRange[1]), 0, {}],
		];
	} else {
		option.series[0].data = JSON.parse(JSON.stringify(emptyLineData))
		option.tooltip.show = false
		option.axisPointer.show = false
		option.series[0].lineStyle.width = 0
		option.yAxis.splitNumber = 5
		option.yAxis.max = 5
		option.yAxis.min = 0
	}

	if (taskQuickMark !== 'range') {
		const data = option.series[0].data;
		let highLightIdx = -1;
		let coordItem;
		if (taskQuickMark === 'last') {
			coordItem = data[data.length - 1];
			highLightIdx = stats.length - 1
		} else {
			coordItem = data[data.length - 2];
			highLightIdx = stats.length - 2
		}
		const coord = [coordItem[0], coordItem[1]];

		if (highLightIdx > -1) {
			option.series[0].markPoint = {
				label: {
					formatter: `${taskQuickMark === 'last' ? '最新一次监测' : '上次监测'}`,
					position: 'top',
				},
				data: [{ coord }],
				symbolSize: 24,
				itemStyle: {
					color: '#F1443C',
				},
			};
		} else {
			option.series[0].markPoint = {};
		}
	}
	const getChart = e => {
		setChart(e);
	};
	if (myChart) {
		myChart.clear()
		myChart.setOption(option);
	}
	return (
		<Box
			title={
				<>
					发现内容威胁趋势
					<Helper overlay="按风险URL统计" placement="top" />
				</>
			}
			headerLeft={
				<RadioGroup className={s.levelSelect} value={type} onChange={setType}>
					<RadioButton borderless key="_ALL_" className={s.radio}>
						全部
					</RadioButton>
					{Object.entries(WARNING_CATEGORY_KEY_LABEL_MAP.content).map(
						([key, label]) => (
							<RadioButton borderless key={key} className={s.radio}>
								{label}
							</RadioButton>
						)
					)}
				</RadioGroup>
			}
			className={cn(className, s.trend)}
		>
			<ECharts
				className={s.chart}
				option={option}
				getInstance={getChart}
			/>
		</Box>
	);
}

Trend.propTypes = {
	className: PropTypes.string,
	stats: PropTypes.arrayOf(
		PropTypes.shape({
			target: PropTypes.string,
			name: PropTypes.string,
			endTime: PropTypes.string,
		})
	),
	jobId: PropTypes.string,
	dateRask: PropTypes.object,
};

Trend.defaultProps = {
	className: s.vulTrend,
};
